<% content_for :head do %>
  <%= javascript_include_tag "graphing" %>
  <%= javascript_include_tag "tweets" %>
  <%= javascript_include_tag "//platform.twitter.com/widgets.js", charset: "utf-8", async: "async" %>
<% end %>

<% grouped_events = @agent.events.order("id desc").limit(2000).group_by {|e| e.payload[:filter] || e.payload[:match] }%>
<% if grouped_events.length > 0 %>
  <% if @agent.options[:generate] == "events" %>
    <h3>Recent Tweets</h3>
    <% grouped_events.each do |filter, group| %>
      <div class="filter-group tweets">
        <div class='filter'><%= filter %></div>
        <% group.each do |event| %>
          <% tweet = event.payload %>
          <% text = tweet.dig(:extended_tweet, :full_text) %>
          <% next unless text.present? %>
          <% screen_name = tweet.dig(:user, :screen_name) %>
          <div class='tweet'><span class="tweet-body" data-tweet-id='<%= tweet[:id_str] %>'><span class="tweet-plain" title="Click to expand"><%= link_to "@#{screen_name}", "https://twitter.com/#{URI.encode(screen_name)}" %>: <%= text %> - <%= link_to l(Time.zone.parse(tweet[:created_at]), format: :long), "https://twitter.com/#{URI.encode(screen_name)}/status/#{URI.encode(tweet[:id_str])}" %></span></span> (<%= link_to 'event', event_path(id: event.id) %>)</div>
        <% end %>
      </div>
    <% end %>

  <% else %>

    <h3>Recent Tweet Trends</h3>
    <% grouped_events.each.with_index do |(filter, group), index|  %>
      <div class="filter-group counts">
        <div class='filter'><%= link_to filter, "https://twitter.com/search?q=#{CGI::escape filter}", :target => "blank" %></div>

        <div class="chart-container group-<%= index.to_s %>">
          <div class="y-axis"></div>
          <div class="chart"></div>
          <div class="timeline"></div>
        </div>

        <script>
          $(function() {
            var $chart = $(".chart-container.group-<%= index.to_s %>").last();
            var data = <%= Utils.jsonify(group.select {|e| e.payload[:count].present? }.sort_by {|e| e.payload[:time] }.map {|e| { :x => e.payload[:time].to_i, :y => e.payload[:count].to_i } }) %>;
            var name = <%= Utils.jsonify(filter) %>;

            renderGraph($chart, data, [], name);
          });
        </script>
      </div>
    <% end %>

  <% end %>
<% else %>
  <p>
    No recent tweets found.
  </p>
<% end %>
